package com.ruoyi.violate.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ExecutorService;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.violate.domain.BusinessCounselor;
import com.ruoyi.violate.domain.ViolateTilte;
import com.ruoyi.web.controller.common.PageReadListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.ruoyi.violate.mapper.ProductDataMapper;
import com.ruoyi.violate.domain.ProductData;
import com.ruoyi.violate.service.IProductDataService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-06-02
 */
@Service
@Slf4j
public class ProductDataServiceImpl implements IProductDataService 
{
    @Autowired
    private ProductDataMapper productDataMapper;

    @Autowired
    private BusinessCounselorServiceImpl businessCounselorService ;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ProductData selectProductDataById(Long id)
    {
        return productDataMapper.selectProductDataById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param productData 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ProductData> selectProductDataList(ProductData productData)
    {
        return productDataMapper.selectProductDataList(productData);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param productData 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertProductData(ProductData productData)
    {
        return productDataMapper.insertProductData(productData);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param productData 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateProductData(ProductData productData)
    {
        return productDataMapper.updateProductData(productData);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteProductDataByIds(Long[] ids)
    {
        return productDataMapper.deleteProductDataByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteProductDataById(Long id)
    {
        return productDataMapper.deleteProductDataById(id);
    }

    /**
     * 导入数据tilte表
     * @param filePath
     * @return
     */
    @Override
    public int importFile(String filePath) throws IOException {

        ExecutorService executor = ThreadUtil.newExecutor(5);

        executor.execute(() ->{
            String path = RuoYiConfig.getProfile() + filePath.substring(8, filePath.length());
            System.out.println(path);

            File file = new File(path);
            MultipartFile files = getMultipartFile(file);
            ExcelReader reader = null;
            try {
                reader = ExcelUtil.getReader(files.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        reader.addHeaderAlias("商品id", "commodityId");
        reader.addHeaderAlias("商品类目", "commodityClass");
        reader.addHeaderAlias("自定义分类", "classify");
        reader.addHeaderAlias("价格", "commodityPrice");
        reader.addHeaderAlias("最低促销价", "promotionalPrice");
        reader.addHeaderAlias("发布时间", "releaseTime");
        reader.addHeaderAlias("商品状态", "itemStatus");
        //获取所有的Excel表格中的tilte
        List<ProductData> list = reader.readAll(ProductData.class);

//            List<ProductData> list = new ArrayList<ProductData>();
//            EasyExcel.read(path, ProductData.class, new PageReadListener<ProductData>(dataList -> {
//                for (ProductData productData : dataList) {
//                    log.info("读取到一条数据{}", JSON.toJSONString(productData));
//                    list.add(productData) ;
//                }
//            })).sheet().doRead();

            String id = IdUtils.simpleUUID() ;
            String[] split = filePath.split("/");
            String shopName = split[6].split("旗舰店")[0] ;
            //关闭线程
            for(ProductData entity :list){
                entity.setShopName(shopName);
                //在数据库中violate_tilte表中添加tilte数据
                this.insertProductData(entity);
            }
            System.out.println("结束线程");
            executor.shutdown();
        });
        return 1 ;
    }

    public MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int) file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }
    /**
     * 导出数据
     * @param response
     * @param \
     */
    public void export(HttpServletResponse response, ProductData productData) throws Exception {
        //全店数据
        List<ProductData> list = this.selectProductDataList(productData);

        //生意参谋数据
        BusinessCounselor businessCounselor = new BusinessCounselor();
        businessCounselor.setParams(productData.getParams());
        businessCounselor.setShopName(productData.getShopName());
        List<BusinessCounselor> businessCounselors = businessCounselorService.selectBusinessCounselorList(businessCounselor);

//        ExcelUtil<ViolateTilte> util = new ExcelUtil<ViolateTilte>(ViolateTilte.class);
//        util.exportExcel(response, list, "标题数据");

//        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
//        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        //过滤后的数据，保存为excel表格
        Set<String> includeColumnFiledNames = new HashSet<String>();
        includeColumnFiledNames.add("id");
        includeColumnFiledNames.add("commodityId");
        includeColumnFiledNames.add("commodityClass");
        includeColumnFiledNames.add("classify");
        includeColumnFiledNames.add("commodityPrice");
        includeColumnFiledNames.add("promotionalPrice");
        includeColumnFiledNames.add("releaseTime");
        includeColumnFiledNames.add("itemStatus");
//        EasyExcel.write(response.getOutputStream(), ViolateTilte.class).includeColumnFiledNames(includeColumnFiledNames).sheet("标题数据").doWrite(list);
        // EasyExcelUtil.writeExcel(response, list, "标题数据", ViolateTilte.class);

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ProductData.class).build() ;

        ArrayList<ProductData> list1 = new ArrayList<>();
        ArrayList<ProductData> list2 = new ArrayList<>();

        for (ProductData pro : list) {
            if (pro.getPromotionalPrice().equals("")){
                list1.add(pro) ;
                if (Double.parseDouble(pro.getCommodityPrice()) <=16){
                    list2.add(pro) ;
                }
            }else if (Double.parseDouble(pro.getCommodityPrice()) <=8 ){
                list2.add(pro) ;
            }
            pro.setCommodityClass1(pro.getCommodityClass().split(">>")[0]);
        }


        Set<BusinessCounselor> list3 = new TreeSet<>(Comparator.comparing(BusinessCounselor::getProductId));
//        ArrayList<BusinessCounselor> list3 = new ArrayList<>();


        for (BusinessCounselor pro : businessCounselors) {
            if (!pro.getProductAdds().equals("0") || !pro.getProductVisitors().equals("0")){
                list3.add(pro) ;
            }
        }

//        //去重比较：list和list3比较
//        Set<ProductData> list4 = new TreeSet<>(Comparator.comparing(ProductData::getCommodityId));
//        for (ProductData data : list) {
//            boolean sign = true ;
//            for (BusinessCounselor counselor : list3) {
//                if (data.getCommodityId().equals(counselor.getProductId())){
//                    sign = false ;
//                }
//            }
//            if (sign){
//                list4.add(data) ;
//            }
//        }
//
//        ArrayList<ProductData> list5 = new ArrayList<>();
//        ArrayList<ProductData> list6 = new ArrayList<>();
//        int count = 0 ;
//        for (ProductData data : list4) {
//            if (count < list4.size()/2){
//                list5.add(data) ;
//            }else {
//                list6.add(data) ;
//            }
//            count++ ;
//        }

        WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "总表").build() ;
        excelWriter.write(list, writeSheet1);

        WriteSheet writeSheet2 = EasyExcel.writerSheet(2, productData.getShopName()+"单品宝").build() ;
        excelWriter.write(list1, writeSheet2);

        WriteSheet writeSheet3 = EasyExcel.writerSheet(3, productData.getShopName()+"删除").build() ;
        excelWriter.write(list2, writeSheet3);

        WriteSheet writeSheet4 = EasyExcel.writerSheet(4, "生意参谋去重后的数据").build() ;
        excelWriter.write(list3, writeSheet4);

//        WriteSheet writeSheet4 = EasyExcel.writerSheet(4, "对比删除后的无流量数据").build() ;
//        excelWriter.write(list4, writeSheet4);
//
//        WriteSheet writeSheet5 = EasyExcel.writerSheet(5, "对比删除后的无流量数据01").build() ;
//        excelWriter.write(list5, writeSheet5);
//
//        WriteSheet writeSheet6 = EasyExcel.writerSheet(6, "对比删除后的无流量数据02").build() ;
//        excelWriter.write(list6, writeSheet6);

        excelWriter.finish();
        response.flushBuffer();
    }

    /**
     * 选择删除
     * @param
     * @return
     */
    @Override
    public int deleteSelectList(ProductData productData){
        if (productData.getShopName()==null
                && productData.getCommodityClass()==null
                && productData.getCommodityPrice()==null
                && productData.getPromotionalPrice()==null
                && productData.getClassify()==null
                && productData.getCommodityId()==null
                && productData.getReleaseTime() ==null
                && productData.getItemStatus() == null){
            return 1 ;
        }
        return productDataMapper.deleteSelectList(productData) ;
    }

    /**
     * 一键全删
     * @return 结果
     */
    @Override
    public int deleteViolateTitleAll(){
        return productDataMapper.deleteViolateTitleAll();
    }


}
